<template>
  <div class="exam-detail-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>考试详情 (ID: {{ examId }})</span>
          <el-button @click="goBack" style="margin-left: auto;">返回列表</el-button>
          <el-button v-if="!isStudent" type="primary" @click="goStatistics" style="margin-left: 8px;">统计</el-button>
        </div>
      </template>
      <div v-if="isLoading">正在加载考试详情...</div>
      <div v-else-if="examData">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="考试标题">{{ examData.title }}</el-descriptions-item>
          <el-descriptions-item label="状态">
             <el-tag :type="getStatusTagType(examData.status)">{{ getStatusText(examData.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDateTime(examData.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDateTime(examData.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="考试时长">{{ examData.duration }} 分钟</el-descriptions-item>
          <el-descriptions-item label="总分">{{ examData.totalScore }}</el-descriptions-item>
          <el-descriptions-item label="及格分">{{ examData.passScore ?? '-' }}</el-descriptions-item>
          <el-descriptions-item label="组题方式">{{ examData.questionSelectionMode === 'MANUAL' ? '手动选题' : '随机抽题' }}</el-descriptions-item>
           <el-descriptions-item label="随机题序">{{ examData.randomQuestions ? '是' : '否' }}</el-descriptions-item>
           <el-descriptions-item label="防作弊">{{ examData.preventCheating ? '是' : '否' }}</el-descriptions-item>
           <el-descriptions-item label="显示结果">{{ examData.showResults ? '是' : '否' }}</el-descriptions-item>
           <el-descriptions-item label="发布时间">{{ formatDateTime(examData.publishTime) }}</el-descriptions-item>
           <el-descriptions-item label="创建者ID">{{ examData.creatorId }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(examData.createTime) }}</el-descriptions-item>
           <el-descriptions-item label="更新时间">{{ formatDateTime(examData.updateTime) }}</el-descriptions-item>
           <el-descriptions-item label="考试描述" :span="2">{{ examData.description || '-' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 关联班级 (仅教师/管理员可见) -->
        <template v-if="!isStudent">
            <el-divider content-position="left">关联班级</el-divider>
            <div v-if="examData.classes && examData.classes.length > 0" class="related-items">
              <el-tag v-for="cls in examData.classes" :key="cls.id" style="margin-right: 8px; margin-bottom: 8px;">
                {{ cls.name }}
              </el-tag>
            </div>
            <div v-else>
              <el-text type="info">未关联任何班级</el-text>
            </div>
        </template>

        <!-- 考试题目 (仅教师/管理员可见) -->
        <template v-if="!isStudent">
            <el-divider content-position="left">考试题目</el-divider>
            <div v-if="examData.questions && examData.questions.length > 0">
               <el-table :data="examData.questions" style="width: 100%" border size="small">
                  <el-table-column type="index" label="序号" width="60"></el-table-column>
                  <el-table-column prop="id" label="题目ID" width="80"></el-table-column>
                  <el-table-column label="题干预览" min-width="250">
                      <template #default="{ row }">
                        {{ stripHtml(row.content).substring(0, 100) + (stripHtml(row.content).length > 100 ? '...' : '') }}
                      </template>
                  </el-table-column>
                  <el-table-column label="类型" width="100">
                      <template #default="{ row }">
                        {{ getQuestionTypeText(row.type) }}
                      </template>
                  </el-table-column>
                   <el-table-column prop="score" label="分数" width="80"></el-table-column>
                   <el-table-column prop="difficulty" label="难度" width="80"></el-table-column>
                   <el-table-column prop="knowledgePoint" label="知识点" width="150"></el-table-column>
               </el-table>
            </div>
             <div v-else>
              <el-text type="info">未包含任何题目</el-text>
            </div>
        </template>

         <!-- TODO: 添加学生成绩列表等 -->
      </div>
      <div v-else>
         <el-empty description="无法加载考试详情"></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { ElCard, ElDescriptions, ElDescriptionsItem, ElTag, ElButton, ElEmpty, ElMessage, ElDivider, ElTable, ElTableColumn, ElText } from 'element-plus';
import { getExamDetail } from '@/services/examService';

const route = useRoute();
const router = useRouter();
const store = useStore();

const isAdmin = computed(() => store.getters.isAdmin);
const isTeacher = computed(() => store.getters.isTeacher);
const isStudent = computed(() => !isAdmin.value && !isTeacher.value && store.getters.isAuthenticated);

const examId = ref(route.params.id);
const isLoading = ref(false);
const examData = ref(null);

const fetchDetails = async () => {
  if (!examId.value) {
    ElMessage.error('无效的考试ID');
    router.push('/exams');
    return;
  }
  isLoading.value = true;
  try {
    const response = await getExamDetail(examId.value);
    if (response && response.success && response.data) {
      examData.value = response.data;
    } else {
      ElMessage.error(response.message || '获取考试详情失败');
       examData.value = null;
    }
  } catch (error) {
    console.error("Error fetching exam detail:", error);
     ElMessage.error('加载考试详情时出错');
     examData.value = null;
  } finally {
    isLoading.value = false;
  }
};

// 辅助函数：移除 HTML 标签
const stripHtml = (html) => {
  if (!html) return '';
  let doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
}

// 辅助函数：获取题目类型文本
const getQuestionTypeText = (type) => {
    const map = {
        SINGLE_CHOICE: '单选',
        MULTIPLE_CHOICE: '多选',
        TRUE_FALSE: '判断',
        FILL_IN_BLANK: '填空', // 假设后端是 FILL_BLANK
        SHORT_ANSWER: '简答'
    };
    return map[type] || type;
}

// 格式化日期时间 (与 ExamList.vue 中的逻辑相同，可以考虑提取到 utils)
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  try {
    return new Date(dateTimeString).toLocaleString();
  } catch (e) {
    return dateTimeString;
  }
};

// 获取状态文字 (与 ExamList.vue 中的逻辑相同)
const getStatusText = (status) => {
  const map = {
    DRAFT: '草稿',
    PUBLISHED: '已发布',
    IN_PROGRESS: '进行中',
    ENDED: '已结束'
  };
  return map[status] || status;
};

// 获取状态标签类型 (与 ExamList.vue 中的逻辑相同)
const getStatusTagType = (status) => {
  const map = {
    DRAFT: 'info',
    PUBLISHED: 'success',
    IN_PROGRESS: 'warning',
    ENDED: undefined
  };
  return map[status];
};

const goBack = () => {
  router.push('/exams');
};

const goStatistics = () => {
  router.push({ name: 'ExamStatistics', params: { id: examId.value } });
};

onMounted(() => {
  fetchDetails();
});
</script>

<style scoped>
.exam-detail-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-divider {
    margin: 30px 0; /* 增加分割线上下的间距 */
}
.related-items {
    margin-bottom: 15px; /* 班级标签下方留点空隙 */
}
</style> 